package cn.twh.wall.util;

import java.util.Random;

import org.apache.commons.lang3.StringUtils;

/**
 * 随机数工具
 * @author TWH
 *
 */
public class RandomUtil {
	protected static Random random=new Random();
	/**
	 * 
	 * @param rate 最大100
	 * @return 是否成功
	 */
	public static boolean reteTrue(int rate) {
		if(rate>100||rate<0) {
			throw new IllegalArgumentException("function need 0-100 rate,but arg is："+rate);
		}
		return random.nextInt(100)<=rate;
	}
	/**
	 * @param weight 权重 , 总和不能超过int.max且大于0
	 * @return 对应下标
	 */
	public static int weightIndex(int... weight) {
		int weightSum = 0;  
        for (int weightValue : weight) {  
            weightSum += weightValue;  
        }
        int randomNum=random.nextInt(weightSum);
		double stepWeightSum = 0;
		for (int i = 0; i < weight.length; i++) {
			stepWeightSum += weight[i];
			if (randomNum < stepWeightSum) {
				return i;
			}
		}
		return -1;
	}
	public String genNumberLeftPad(int length) {
		String max = StringUtils.leftPad("", length,'9');
		int randomInt = random.nextInt(Integer.parseInt(max));
		return StringUtils.leftPad(String.valueOf(randomInt), length);
	}
}
